﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.IO;
using ReflectionStudio.Core;
using ReflectionStudio.Core.Events;
using ReflectionStudio.Core.FTPClient;
using System.Data.OracleClient;
using System.IO;
using Intex.Tools;
namespace WPFExcelReport
{
    public struct vvPACK
    {
        public string PackNr;
        public SortedList<string, DataRow> WBBSTnr;
    }
    public struct vvVKPOS
    {
        public DataRow dwVKPOS;
        public SortedList<string, vvPACK> listVVPACK;
    }
    public class DSTWBQILISTReport : BaseReport
    {
        #region ----------------PROPERTIES----------------------------------
        byte[] b;
        public IntexReptServBLClient proxy;
        public OracleConnection OracleDB;
        string WBBAUFKRS;
        string WBBAUFLFD;
        string WBBAUFPOS;
        string WBBALIEFSCH;
        string VKAUFNum = "";
        string WBBTAX;
        string DocType;
        string CellName = "";
        string CellValue = "";
        string strCompany;
        string orderComments = "备注：";
        string strExcelFile;
        public string Customer = "";
        public string Address = "";
        string DateCurrent = "";
        public string PrintType = "JustExcel";
        public List<vvVKPOS> listVKPOS = new List<vvVKPOS>();
        public FTPClient ftpClient;
        string finalfilename = "";
        private IntexTools IntexTools; 
        #endregion
        public DSTWBQILISTReport()
            : base()
        {

        }
        public DSTWBQILISTReport(Dictionary<string, object> dicParamater)
            : base(dicParamater)
        {
            DocType = dicParamater["DocType"].ToString().Trim();
            strCompany = dicParamater["Company"].ToString().Trim();
            strExcelFile = dicParamater["ExcelFile"].ToString().Trim();
            DateCurrent = DateTime.Now.Year.ToString() + "年" + DateTime.Now.Month.ToString() + "月" + DateTime.Now.Day.ToString() + "日";
            OracleDB = (OracleConnection)dicParamater["OracleDB"];
            proxy = (IntexReptServBLClient)dicParamater["proxy"];
            IntexTools = new IntexTools(OracleDB, proxy, "");
        }

        private int FillInEXCEL()
        {
            int result = 1;
            try
            {
                DataTable tbWBBST = dsSource.Tables["WBBST"];
                DataTable tbWBFEHL = dsSource.Tables["WBFEHL"];
                BaseFunction m_bf = new BaseFunction(OracleDB, proxy);
                double STKLG = 0.0;

                int rowx = 2;
                int x = 0;
                string error = "";
                string WBBBEM = ""; 
                foreach (DataRow wbrow in tbWBBST.Rows)
                {
                    #region========YDType=============
                    string YDType = "YD0";
                    string ftype, art, var, color, finish;
                    string labeltype;
                    double YLength = 0;
                    ftype = wbrow["WBBWAKZ"].ToString();
                    art = wbrow["WBBART"].ToString();
                    var = wbrow["WBBVAR"].ToString();
                    color = wbrow["WBBFARBE"].ToString();
                    finish = wbrow["WBBBESCHICH"].ToString();
                    labeltype = IntexTools.GetABAUFM(ftype, art, var, color, finish);
                    switch (labeltype)
                    {
                        case "41":
                        case "51":
                            YDType = "YD1";
                            break;
                        default:
                            YDType = "YD0";
                            break;
                    }
                    string SSTKLG = wbrow["WBBISTKLG"].ToString();
                    if (SSTKLG.Trim() == "")
                        SSTKLG = "0";
                    STKLG = System.Math.Round(System.Convert.ToDouble(SSTKLG) * 0.001, 2);
                    YLength = System.Math.Round(STKLG / 0.9144, 0);
                    if (YDType == "YD1")
                    { 
                        STKLG = System.Math.Round(STKLG, 1);
                        YLength = System.Math.Round(YLength, 1);
                    }
                    else
                    {
                        STKLG = System.Math.Round(STKLG, 0);
                    }
                    #endregion
                    x++;
                    exAgent.SetCellValue(rowx + x, 1, x);
                    //机号	日期	检验员	花号	坯布卷号	坯布码长	修布工号	成品卷号	成品码长M	成品码长Y	实际门幅	有效门幅	纬密	拼匹情况	库位	备注
                    exAgent.SetCellValue(rowx + x, 2, wbrow["WBEWMLFDNR"].ToString());
                    exAgent.SetCellValue(rowx + x, 3, wbrow["WBEWBUCHDAT"].ToString());
                    exAgent.SetCellValue(rowx + x, 4, wbrow["WBEWBUCHBEN"].ToString());
                    exAgent.SetCellValue(rowx + x, 5, wbrow["WBBART"].ToString().Trim() + "-" + wbrow["WBBFARBE"].ToString().Trim());
                    exAgent.SetCellValue(rowx + x, 6, wbrow["RSTKNR"].ToString());
                    double  RSTKLG = System.Math.Round(System.Convert.ToDouble(wbrow["RSTKLG"].ToString()) * 0.001, 2);
                    exAgent.SetCellValue(rowx + x, 7, RSTKLG);
                    exAgent.SetCellValue(rowx + x, 8, wbrow["WBBDPART"].ToString());
                    exAgent.SetCellValue(rowx + x, 9, wbrow["WBEWSTKNR"].ToString());
                  
                    exAgent.SetCellValue(rowx + x, 10, STKLG);
                    exAgent.SetCellValue(rowx + x, 11, YLength);
                    string SWBBSBRT = wbrow["WBBSBRT"].ToString();
                    if (SWBBSBRT.Trim() == "")
                        SWBBSBRT = "0";
                    double WBBSBRT = System.Math.Round(System.Convert.ToDouble(SWBBSBRT) * 0.001, 1);
                    exAgent.SetCellValue(rowx + x, 12, WBBSBRT);
                    string SWBBIBRT = wbrow["WBBIBRT"].ToString();
                    if (SWBBIBRT.Trim() == "")
                        SWBBIBRT = "0";
                    double WBBIBRT = System.Math.Round(System.Convert.ToDouble(SWBBIBRT) * 0.001, 1);
                    exAgent.SetCellValue(rowx + x, 13, WBBIBRT);
                    WBBBEM = wbrow["WBBBEM"].ToString();
                    exAgent.SetCellValue(rowx + x, 14, WBBBEM.Substring(4, 3));
                    exAgent.SetCellValue(rowx + x, 15, WBBBEM.Substring(6));
                    exAgent.SetCellValue(rowx + x, 16, wbrow["WBEWLO"].ToString() + wbrow["WBEWLB"].ToString() + wbrow["WBEWLP"].ToString());
                    exAgent.SetCellValue(rowx + x, 17, wbrow["COMMENTS"].ToString());
                    error = "";
                    if (tbWBFEHL != null)
                    {
                        var query = from dwError in tbWBFEHL.AsEnumerable()
                                    where dwError["WBBSTKNR"].ToString() == wbrow["WBEWSTKNR"].ToString()
                                    select dwError;
                        foreach (DataRow dwError in query)
                        {
                            error += dwError["WBFLGVON"].ToString().Trim()
                                + "-" + dwError["WBFLGVON"].ToString().Trim()
                                + m_bf.Convert8859P1ToGB2312(dwError["CDES"].ToString()).Trim() + ",";
                        }
                        error += "***";
                        error = error.Replace(",***", "");
                    }
                    exAgent.SetCellValue(rowx + x, 18, error);
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            return result;
        }
        private int FillInWBFEHL()
        {
            int result = 1;
            try
            {
                DataTable tbWBFEHL = dsSource.Tables["WBFEHL"];
                BaseFunction m_bf = new BaseFunction(OracleDB, proxy);
                double STKLG = 0.0;
                int rowx = 2;
                int x = 0;
                //序号	日期	检验员	花号	成品卷号	成品码长M	成品码长Y	疵点名称	疵点分数
                exAgent.SetCellValue(2, 1, "序号", true);
                exAgent.SetCellValue(2, 2, "机台", true);
                exAgent.SetCellValue(2, 3, "日期", true);
                exAgent.SetCellValue(2, 4, "检验员", true);
                exAgent.SetCellValue(2, 5, "花号", true);
                exAgent.SetCellValue(2, 6, "成品卷号", true);
                exAgent.SetCellValue(2, 7, "成品码长M", true);
                exAgent.SetCellValue(2, 8, "成品码长Y", true);
                exAgent.SetCellValue(2, 9, "起始", true);
                exAgent.SetCellValue(2, 10, "结束", true);
                exAgent.SetCellValue(2, 11, "疵点代号", true);
                exAgent.SetCellValue(2, 12, "疵点名称", true);
                exAgent.SetCellValue(2, 13, "疵点分数", true);

                foreach (DataRow wbrow in tbWBFEHL.Rows)
                {
                    #region========YDType=============
                    string ftype, art, var, color, finish;
                    string labeltype;
                    double YLength = 0;
                    string YDType = "YD0";
                    ftype = wbrow["WBBWAKZ"].ToString();
                    art = wbrow["WBBART"].ToString();
                    var = wbrow["WBBVAR"].ToString();
                    color = wbrow["WBBFARBE"].ToString();
                    finish = wbrow["WBBBESCHICH"].ToString();
                    labeltype = IntexTools.GetABAUFM(ftype, art, var, color, finish);
                    switch (labeltype)
                    {
                        case "Y1":
                        case "B1":
                            YDType = "YD1";
                            break;
                        default:
                            YDType = "YD0";
                            break;
                    }
                    string SSTKLG = wbrow["WBBISTKLG"].ToString();
                    if (SSTKLG.Trim() == "")
                        SSTKLG = "0";
                    STKLG = System.Math.Round(System.Convert.ToDouble(SSTKLG) * 0.001, 2);
                    YLength = System.Math.Round(STKLG / 0.9144, 0);
                    if (YDType == "YD1")
                    {
                        STKLG = System.Math.Round(STKLG, 1);
                        YLength = System.Math.Round(YLength, 1);
                    }
                    else
                    {
                        STKLG = System.Math.Round(STKLG, 0);
                    }
                    #endregion
                    x++;
                    exAgent.SetCellValue(rowx + x, 1, x);
                    //序号	日期	检验员	花号	成品卷号	成品码长M	成品码长Y	疵点名称	疵点分数
                    exAgent.SetCellValue(rowx + x, 2, wbrow["WBEWMLFDNR"].ToString());
                    exAgent.SetCellValue(rowx + x, 3, wbrow["WBEWBUCHDAT"].ToString());
                    exAgent.SetCellValue(rowx + x, 4, wbrow["WBEWBUCHBEN"].ToString());
                    exAgent.SetCellValue(rowx + x, 5, wbrow["WBBART"].ToString().Trim() + "-" + wbrow["WBBFARBE"].ToString().Trim());
                    exAgent.SetCellValue(rowx + x, 6, wbrow["WBBSTKNR"].ToString());                  
                    exAgent.SetCellValue(rowx + x, 7, STKLG);
                    exAgent.SetCellValue(rowx + x, 8, YLength);
                    exAgent.SetCellValue(rowx + x, 9, wbrow["WBFLGVON"].ToString());
                    exAgent.SetCellValue(rowx + x, 10, wbrow["WBFLGBIS"].ToString());
                    exAgent.SetCellValue(rowx + x, 11, wbrow["WBFFSCHL"].ToString());
                    exAgent.SetCellValue(rowx + x, 12, m_bf.Convert8859P1ToGB2312(wbrow["CDES"].ToString()));
                    exAgent.SetCellValue(rowx + x, 13, m_bf.Convert8859P1ToGB2312(wbrow["CVALUE"].ToString()));
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            return result;
        }



        private void CheckDirectory(string root, string sub, string year, string month, string day)
        {
            try
            {
                string drlocal = root;
                string dr0 = "";

                #region========================LOCAL=====================
                drlocal = Path.Combine(PathHelper.ApplicationPath, @"Report");
                if (!Directory.Exists(drlocal))
                    Directory.CreateDirectory(drlocal);

                drlocal = Path.Combine(drlocal, "Sales");
                if (!Directory.Exists(drlocal))
                    Directory.CreateDirectory(drlocal);
                #endregion
                drlocal = root;
                drlocal = Path.Combine(drlocal, sub);
                if (!Directory.Exists(drlocal))
                    Directory.CreateDirectory(drlocal);
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }

        private string CreateFile(string orderno)
        {
            string filename = "";
            string sheetName = "";
            string Standard = "WBQILIST";
            string filePath = Path.Combine(PathHelper.ApplicationPath, @"Report\DST\DSTStandard.xls");
            try
            {
                string pwd = "";
                sheetName = orderno;
                exAgent.Open(filePath);
                exAgent.Company = strCompany;
                exAgent.strExcelFile = strExcelFile;
                string newfilename = orderno;
                exAgent.CreateNewSheet(newfilename, Standard, "成品检验报表", pwd);
                filename = exAgent.FileName;
                exAgent.SetCurrentSheet(1);
                FillInEXCEL();
                exAgent.SetCurrentSheet(2);
                exAgent.RenameSheet("疵点报表");
                FillInWBFEHL();
                finalfilename = exAgent.FileName;
                exAgent.Save();
                exAgent.Close();

            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            return filename;
        }

        public void CheckFTPDir(string root, string sub, string KRS, string year, string month, string day, string ordernumber = "")
        {
            string createdtimefile = PathHelper.ApplicationPath + "\\ftp.txt";
            string newfile = "/创建于" + year + month + day;
            try
            {
                string drlocal = root;
                if (!ftpClient.DirectoryExists(drlocal))
                {
                    ftpClient.CreateDirectory(drlocal);
                }
                drlocal = drlocal + "/" + sub;
                if (!ftpClient.DirectoryExists(drlocal))
                {
                    ftpClient.CreateDirectory(drlocal);
                }
                drlocal = drlocal + "/" + KRS;
                if (!ftpClient.DirectoryExists(drlocal))
                {
                    ftpClient.CreateDirectory(drlocal);
                }
                drlocal = drlocal + "/" + year;
                if (!ftpClient.DirectoryExists(drlocal))
                {
                    ftpClient.CreateDirectory(drlocal);
                }
                drlocal = drlocal + "/" + month;
                if (!ftpClient.DirectoryExists(drlocal))
                {
                    ftpClient.CreateDirectory(drlocal);
                    ftpClient.PutFile(createdtimefile, drlocal + newfile);
                }
                if (ordernumber != "")
                {
                    drlocal = drlocal + "/" + ordernumber;
                    if (!ftpClient.DirectoryExists(drlocal))
                    {
                        ftpClient.CreateDirectory(drlocal);
                        ftpClient.PutFile(createdtimefile, drlocal + newfile);
                    }
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        private void FTPShareFile(string KRS, string year, string month, string day, string ordernumer, string fileType)
        {
            string VVLIEFSCH = System.Convert.ToInt64(ordernumer).ToString();
            string fileabsname = VVLIEFSCH + "_" + DateTime.Now.Day.ToString() + "_"
                    + DateTime.Now.ToShortTimeString().Replace(":", "_").Replace(" ", "_").Replace("/", "_") + "_" + VVLIEFSCH + ".xls";
            string localFile = @"C:\Windows\Temp\" + fileabsname;
            string tempfile = "";
            try
            {
                ftpClient.Open();
                ftpClient.Login();
                string root = "/Sales/";
                ftpClient.SetCurrentDirectory("/");
                CheckFTPDir("/Sales", "发货单", KRS, year, month, day);
                string destfile;
                filename = root + "发货单/" + KRS + "/" + year + "/" + month + "/" + fileabsname;
                if (ftpClient.FileExists(filename))
                {
                    ftpClient.RemoveFile(filename);
                }

                #region==========产生文件，复制到服务器=======================
                destfile = filename;
                tempfile = CreateFile(fileabsname);
                localFile = tempfile;
                if (ftpClient.FileExists(destfile))
                {
                    ftpClient.RemoveFile(destfile);
                }
                ftpClient.PutFile(tempfile, destfile);
                localFile = @"C:\Windows\Temp\" + fileabsname;
                ftpClient.GetFile(filename, localFile, false);
                #endregion
                #region=========打开服务器上的文件进行浏览========================
                if (fileType == "OpenExcel" ||
                    fileType == "EXCEL"
                    )
                {
                    localFile = @"C:\Windows\Temp\" + fileabsname;
                    if (File.Exists(localFile))
                    {
                        File.Delete(localFile);
                    }
                    File.Move(tempfile, localFile);
                    System.Diagnostics.Process.Start("EXCEL.EXE", localFile);
                }
                #endregion
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            finally
            {
                if (File.Exists(tempfile))
                {
                    File.Delete(tempfile);
                }
            }
        }
        private void CreateFile(string KRS, string year, string month, string day, string ordernumer, string fileType)
        {
            string VVLIEFSCH = ordernumer;
            string fileabsname = ordernumer + ".xls";
            if (!System.IO.Directory.Exists(@"C:\intex.w"))
            {
                System.IO.Directory.CreateDirectory(@"C:\intex.w");
            }
            if (!System.IO.Directory.Exists(@"C:\intex.w\Report"))
            {
                System.IO.Directory.CreateDirectory(@"C:\intex.w\Report");
            }
            if (!System.IO.Directory.Exists(@"C:\intex.w\Report\验布"))
            {
                System.IO.Directory.CreateDirectory(@"C:\intex.w\Report\验布");
            }
            string localFile = @"C:\intex.w\Report\验布\" + fileabsname;
            string tempfile = "";
            try
            {
                tempfile = CreateFile(fileabsname);
                System.IO.File.Copy(tempfile, localFile, true);
                #region=========打开服务器上的文件进行浏览========================
                if (fileType == "OpenExcel" ||
                    fileType == "EXCEL"
                    )
                {
                    System.Diagnostics.Process.Start("EXCEL.EXE", localFile);
                }
                #endregion
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }

        public override void WriteExcelReport(string fileType)
        {
            bool IsFTP = false;
            try
            {
                #region==========准备程序===================
                string year = System.DateTime.Now.Year.ToString();
                string month = Right("00" + System.DateTime.Now.Month.ToString(), 2);
                string day = Right("00" + System.DateTime.Now.Day.ToString(), 2);
                string today = year + month + day;
                strExcelFile = @"DST\DSTStandard.xls";
                string newfilename = "QIWB" + today;
                exAgent.CheckWorkBook(newfilename);
                #endregion
                if (IsFTP)
                {
                    FTPShareFile(year, year, month, day, newfilename, fileType);
                }
                else
                {
                    CreateFile(year, year, month, day, newfilename, fileType);
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }

    }
}
